package com.db.bankapp.service;

import com.db.bankapp.domain.Bank;
import com.db.bankapp.domain.Client;
import com.db.bankapp.domain.ClientBuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * Created by Java Student on 8/22/2014.
 */
public class BankDataLoaderService {
    private BankDataLoaderService() {}

    public static void feedBank(Bank bank, Scanner sc) {
        sc.useDelimiter(";");
        while (sc.hasNext()) {
            String accountType = getParameterValue(sc.next());
            switch (accountType) {
                case "c":
                    bank.addClient(parseClientWithCheckingAccount(sc));
                    break;
                case "s":
                    bank.addClient(parseClientWithSavingAccount(sc));
                    break;
                default:
                    throw new RuntimeException("Wrong file format!");
            }
        }
    }

    public static void feedBank(Bank bank, String pathToFeed) {
        try (Scanner sc = new Scanner(new File(pathToFeed))) {
            feedBank(bank, sc);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static Client parseClientWithCheckingAccount(Scanner sc) {
            int balance = Integer.parseInt(getParameterValue(sc.next()));
            int overdraft = Integer.parseInt(getParameterValue(sc.next()));
            String name = getParameterValue(sc.next());
            String gender = getParameterValue(sc.next());
            return setGender(ClientBuilder.newClient(name).withAccount(
                    Bank.createCheckingAccount(balance, overdraft)), gender).build();
    }

    private static Client parseClientWithSavingAccount(Scanner sc) {
        int balance = Integer.parseInt(getParameterValue(sc.next()));
        String name = getParameterValue(sc.next());
        String gender = getParameterValue(sc.next());
        return setGender(ClientBuilder.newClient(name).withAccount(Bank.createSavingAccount(balance)), gender).build();
    }

    private static ClientBuilder setGender(ClientBuilder builder, String gender) {
        if ("f".equals(gender)) {
            return builder.female();
        }
        if ("m".equals(gender)) {
            return builder.male();
        }
        throw new IllegalArgumentException("Gender must be f or m!");
    }

    private static String getParameterValue(String valuePair) {
        return valuePair.split("=")[1];
    }
}
